from django.http import JsonResponse
import json
from common.models import Customer

from django.core.paginator import Paginator, EmptyPage
from django.db.models import Q

import traceback
from config import settings
from django_redis import get_redis_connection
# def dispatcher(request):
#     # 将请求参数统一放入request的params属性中，方便后续处理

#     # 根据session判断用户是否是登录的管理员用户
#     if 'usertype' not in request.session:
#         return JsonResponse({
#             'ret': 302,
#             'msg': '未登录',
#             'redirect': '/mgr/sign.html'},
#             status=302)

#     if request.session['usertype'] != 'mgr':
#         return JsonResponse({
#             'ret': 302,
#             'msg': '用户非mgr类型',
#             'redirect': '/mgr/sign.html'},
#             status=302)

#     # get请求参数在url中，通过request对象的get属性获取
#     if request.method == 'GET':
#         request.params = request.GET

#     # post/put/delete请求参数从request对象的body属性中获取
#     elif request.method in ['POST', 'PUT', 'DELETE']:
#         # 根据接口，post/put/delete请求的消息体都是json格式
#         request.params = json.loads(request.body)
    
#     # 根据不同action分派给不同函数进行处理
#     action = request.params['action']
#     if action == 'list_customer':
#         return listcustomers(request)
#     elif action == 'add_customer':
#         return addcustomer(request)
#     elif action == 'modify_customer':
#         return modifycustomer(request)
#     elif action == 'del_customer':
#         return deletecustomer(request)
#     else:
#         return JsonResponse({'ret': 1, 'msg': '不支持该类型http请求'})

# 获取一个和redis服务的连接
rconn = get_redis_connection("default")
def listcustomers(request):

    try:
        # 查看是否有 关键字 搜索 参数
        keywords = request.params.get('keywords',None)
        
        # 要获取的第几页
        pagenum = request.params['pagenum']

        # 每页要显示多少条记录
        pagesize = request.params['pagesize']

        # 先查看缓存中是否有
        cacheFiled = f"{pagesize}|{pagenum}|{keywords}" # 缓存filed

        cacheObj = rconn.hget(settings.CK.CustomerList,
                              cacheFiled)

        # 缓存中有，需要反序列化
        if cacheObj:
            print("缓存命中")
            retObj = json.loads(cacheObj)
        
        # 如果缓存中没有，再去数据库中查询
        else:
            # 返回一个 QuerySet 对象 ，包含所有的表记录
            qs = Customer.objects.values().order_by('-id')

            if keywords:
                conditions = [Q(name__contains=one) for one in keywords.split(' ') if one]
                query = Q()
                for condition in conditions:
                    query &= condition
                qs = qs.filter(query)


            
            # 使用分页对象，设定每页多少条记录
            pgnt = Paginator(qs, pagesize)

            # 从数据库中读取数据，指定读取其中第几页
            page = pgnt.page(pagenum)

            # 将 QuerySet 对象 转化为 list 类型
            retlist = list(page)

            retObj = {'ret': 0, 'retlist': retlist, 'total': pgnt.count}

            # 存入缓存
            rconn.hset(settings.CK.CustomerList,
                       cacheFiled,
                       json.dumps(cacheObj))

        # total指定了 一共有多少数据
        return JsonResponse(retObj)
        # return JsonResponse({'ret': 0, 'retlist': retlist,'total': pgnt.count})

    except EmptyPage:
        return JsonResponse({'ret': 0, 'retlist': [], 'total': 0})

    except:
        return JsonResponse({'ret': 2,  'msg': f'未知错误\n{traceback.format_exc()}'})

# def listcustomers(request):
#     # 返回一个QuerySet对象，包含所有的表记录
#     qs = Customer.objects.values()

#     # 将QuerySet对象转化为List类型
#     # 否则不能被转化为JSON字符串
#     retlist = list(qs)

#     return JsonResponse({'ret': 0, 'retlist': retlist})
    
def addcustomer(request):
    info = request.params['data']
    # 从请求消息中获得要添加客户的信息
    # 并插入到数据库中
    # 返回值就是对应的插入记录
    record = Customer.objects.create(name=info['name'],
                                     phonenumber=info['phonenumber'],
                                     address=info['address'],)
    
    # 数据库更新了，缓存不一致，删除缓存
    rconn.delete(settings.CK.CustomerList)

    return JsonResponse({'ret': 0, 'id': record.id})
    
def modifycustomer(request):
    # 从请求消息中获取修改客户的信息
    # 找到该客户，并进行修改操作

    customerid = request.params['id']
    newdata = request.params['newdata']

    try:
        # 根据id从数据库中找到相应的客户记录
        customer = Customer.objects.get(id=customerid)
    except Customer.DoesNotExist:
        return {
            'ret': 1,
            'msg': f'id为`{customerid}`的客户不存在'
        }
    
    if 'name' in newdata:
        # 拼写错误，导致不能修改名称
        # Customer.name = newdata['name']
        customer.name = newdata['name']
    if 'phonenumber' in newdata:
        customer.phonenumber = newdata['phonenumber']
    if 'address' in newdata:
        customer.address = newdata['address']

    # 注意，一定要执行save才能将修改信息保存到数据库
    customer.save()
    # 数据库更新了，缓存不一致，删除缓存
    rconn.delete(settings.CK.CustomerList)
    return JsonResponse({'ret': 0})

def deletecustomer(request):

    customerid = request.params['id']

    try:
        # 根据id从数据库中找到相应的客户记录
        customer = Customer.objects.get(id=customerid)
    except Customer.DoesNotExist:
        return {
            'ret': 1,
            'msg': f'id为`{customerid}`的客户不存在'
        }
    # delete方法就将记录从数据库中删除了
    customer.delete()
    # 数据库更新了，缓存不一致，删除缓存
    rconn.delete(settings.CK.CustomerList)
    return JsonResponse({'ret': 0})

from lib.handler import dispatcherBase

Action2Handler = {
    'list_customer': listcustomers,
    'add_customer': addcustomer,
    'modify_customer': modifycustomer,
    'del_customer': deletecustomer,
}

def dispatcher(request):
    return dispatcherBase(request, Action2Handler)

